<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\logic\ShopLogic;
use app\common\model\shop\Category;
use app\common\model\shop\Goods;
use app\common\validate\shop\GoodsValidete;
use think\Db;


/**
 * 会员接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['getCate', 'getList', 'detail'];
    protected $noNeedRight = '*';
    protected $shopLogic = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->shopLogic = new ShopLogic();

    }


    /**
     * 商品分类
     */
    public function getCate() {
        $cate = Category::all(function($query){
            $query->order('weigh', 'desc');
        });

        $this->success('cate', $cate);
    }

    /**
     * 商品列表
     */
    public function getList() {
        $category_id = input('category_id/d', 0);
        $where['switch'] = 1;
        if ($category_id) {
            $where['category_id'] = $category_id;
        }
        $search = input('search/s', '');
        if ($search) {
            $where['name'] = "%$search%";
        }

        $list = Goods::where($where)->order('createtime desc')->paginate(15);

        $this->success('商品列表', $list);
    }


    /** 商品详情*/
    public function detail() {
        $goods_id = input('goods_id/d', 0);
        if (!$goods_id) {
            $this->error('参数传递错误');
        }

        $goods = Goods::get($goods_id);
        $is_zan = 0;
        $is_collect = 0;
        $dbcollect = Db::name('shop_collect');
        if (defined(UID) && UID > 0) {
            $is_zan = $dbcollect->where(['type'=> 1, 'user_id'=>UID, 'goods_id'=>$goods_id])->count();
            $is_collect = $dbcollect->where(['type'=> 0, 'user_id'=>UID, 'goods_id'=>$goods_id])->count();
        }

        $this->success('商品信息', [
            'goods' => $goods,
            'user'  => [
                'is_zan' => $is_zan,
                'is_collect' => $is_collect
            ]
        ]);
    }

    /**
     * 点赞 收藏
     */
    public function zan() {
        $goods_id = input('goods_id/d', 0);
        if (!$goods_id) {
            $this->error('参数传递错误');
        }

        $type = input('type/d', 0); //0=收藏,1=点赞
        if (!in_array($type, [0, 1])) {
            $this->error('type参数错误');
        }
        $dbcollect = Db::name('shop_collect');
        $data = ['user_id'=>UID, 'type'=>$type, 'goods_id'=>$goods_id];
        if ($dbcollect->where($data)->count() > 0) {
            //取消 删除
            $dbcollect->where($data)->delete();
        } else {
            //添加成功
            $dbcollect->insert($data);
        }

        $this->success($type == 0 ? '收藏成功': '点赞成功');
    }




    /**
     * 购买列表
     */
    public function toBuy() {
        //要购买的上皮ids
        $goods_ids = input('goods_ids/a', []);
        if (!$goods_ids) {
            $this->error('参数错误');
        }

        $goods = Goods::where([
            'switch'=> 1,
            'id' => ['in', $goods_ids]
        ])->select();

        $this->success('购买列表', $goods);
    }




    /**
     * 发布
     */
    public function publish()
    {
        (new GoodsValidete())->goCheck();
        $param = $this->request->param();

        $goods = new Goods();
        $res = $goods->allowField(['name', 'category_id', 'introduce', 'price', 'images', 'unit', 'num'])
            ->data($param)
            ->save();

        if ($res) {
            $this->success('发布成功');
        }

        $this->error('发布失败');
    }

    public function purchased(){
        $list = Db::name('shop_order_goods')->alias('g')
        ->join("__SHOP_ORDER__ order","order.id = g.order_id")
        ->where('order.user_id', UID)
        ->where('order.status','gt',0)
        ->order('order.createtime desc')
        ->field("g.*")
        ->paginate(10)
        ->each(function($item){
            $item['goods_info'] = Goods::get($item['goods_id']);
            return $item;
        });

        $this->success('我购买过的商品', $list);
    }


    /** 修改内容***************************************************/

    /**
     * 从购物车删除
     */
    public function delete() {
        $this->shopLogic->delete(UID);

        $this->success('从购物车删除成功');
    }

    /**
     * 我的购物车
     */

    public function cart() {
        //当前会员的购物车
        $cart = Db::name('shop_cart');
        $list = $cart->alias('c')
            ->join('__SHOP_GOODS__ g', 'c.goods_id = g.id')
            ->order('c.createtime desc')
            ->where([
                'c.user_id' => UID,
                'g.switch' => 1
            ])
            ->field(['c.id', 'c.num', 'c.createtime','c.goods_id', 'g.switch','g.name', 'g.price', 'g.image', 'g.origin_price'])
            ->paginate()
            ->each(function ($item, $key) {
                $item['image_text'] = cdnurl($item['image'], true);
                return $item;
            });

        $this->success('我的购物车', $list);
    }

    /**
     * 加入购物车
     */
    public function joinCart() {
        $goods_id = input('goods_id/d', 0);
        $number = input('number/d', 0);

        if (!$goods_id || $goods_id <= 0) {
            $this->error('商品ID错误');
        }
        if ($number <= 0) {
            $this->error('商品数量不能小于0');
        }
        $cart = Db::name('shop_cart');
        if ($cart->where(['user_id' => UID, 'goods_id' => $goods_id])->count() > 0) {
            //修改时间
            $cart->where(['user_id' => UID, 'goods_id' => $goods_id])->setField('createtime', time());
        } else {
            $cart->insert([
                'user_id' => UID,
                'num' => $number,
                'goods_id' => $goods_id,
                'createtime' => time()
            ]);
        }

        $this->success('加入购物车成功');
    }


    /**
     * 购物车生成订单
     */
    public function createOrder() {
        $order_id = $this->shopLogic->createOrder();
        $this->success('订单生成成功', $order_id);
    }


    /**
     * 购物车商品清单
     */
    public function postOrders() {
        $orderid = input('orderid/d', 0);
        $res = $this->shopLogic->postOrders($orderid);
        $this->success('商品清单', $res);
    }


    /**
     * 立即购买
     */
    public function createOrderOne() {
        $order_id = $this->shopLogic->createOrderOne();
        $this->success('订单生成成功', $order_id);
    }

    /**我的购买*/
    public function myBuy() {
        $where['user_id'] = UID;

        //获取所用商品
        $list = Db::name('shop_order_goods')->where('order_id', 'IN', function ($query) {
            $query->name('shop_order')->where(['user_id' => UID])->field('id');
        })->where(['status' => ['neq', 0]])->paginate()->each(function ($item) {
            return $item;
        });

        $this->success('list', $list);
    }
}
